﻿using System;
using System.Globalization;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Data;
using System.Windows;

namespace BrainTechLLC.WPF
{
    /// <summary>   
    /// A type converter for visibility and boolean values.   
    /// </summary>   
    public class VisibilityConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value == null)
                return Visibility.Collapsed;

            Type t = value.GetType();
            bool visibility = false;

            if (t == typeof(string))
            {
                string stringVal = value as string;

                if (!string.IsNullOrEmpty(stringVal))
                {
                    visibility = true;
                }
            }
            else if (t == typeof(bool))
            {
                visibility = (bool)value;
            }
            else if (t == typeof(double))
            {
                double d = (double)value;
                visibility = (d != 0 && d != double.MaxValue && !double.IsNaN(d));
            }
            else
            {
                visibility = true;
            }

            if (parameter != null && parameter.ToString().Equals("NOT", StringComparison.OrdinalIgnoreCase))
            {
                return visibility ? Visibility.Collapsed : Visibility.Visible;
            }
            else
            {
                return visibility ? Visibility.Visible : Visibility.Collapsed;
            }
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (targetType == typeof(bool))
            {
                Visibility visibility = (Visibility)value;
                return (visibility == Visibility.Visible);
            }
            else if (targetType == typeof(Visibility))
            {
                bool b = (bool)value;
                return b ? Visibility.Visible : Visibility.Collapsed;
            }
            else
            {
                throw new Exception("Cannot convert back");
            }
        }
    }
}
